<?php

declare(strict_types=1);

namespace app\common\command\proxy;

use app\common\worker\protocol\Framex;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Connection\AsyncUdpConnection;
use Workerman\Connection\TcpConnection;
use Workerman\Connection\UdpConnection;
use Workerman\Worker;

class Client extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('proxy:client')
            ->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload|status|connections", 'start')
            ->addOption('mode', 'm', Option::VALUE_OPTIONAL, 'Run the workerman server in daemon mode.')
            ->setDescription('the client command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('client');



        $action = $input->getArgument('action');
        $mode = $input->getOption('mode');


        // 重新构造命令行参数,以便兼容workerman的命令
        global $argv;

        $argv = [];

        array_unshift($argv, 'think', $action);

        if ($action == 'restart') {
            $mode = 'd';
        }

        if ($mode == 'd') {
            $argv[] = '-d';
        } else if ($mode == 'g') {
            $argv[] = '-g';
        }

        $worker = new Worker('tcp://0.0.0.0:4455');

        $worker->onConnect = function ($connection) {

            $proxy_connection = new AsyncTcpConnection('tcp://104.207.149.140:4457');
            $proxy_connection->protocol = Framex::class;

            $proxy_connection->pipe($connection);
            $connection->pipe($proxy_connection);
            $proxy_connection->connect();
        };


        Worker::runAll();
    }
}
